﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DataFileApp
{
    public partial class Form1 : Form
    {
        LanguageConverter languageConverter = new LanguageConverter();
        public Form1()
        {
            InitializeComponent();
            //设置默认语言为English
            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en");
        }

        public Form1(string args)
        {
            InitializeComponent();
            path = args;
        }

        string path;
        string jsonStr;
        List<TreeNode> ls_node = new List<TreeNode>();
        TreeNode CurrentSelectedNode;

        private void Loadfile(string filePath)
        {
            jsonStr = Operate.LoadJsonFromFile(filePath);
            Binding(this.treeView1, jsonStr);
            var TopNode = treeView1.TopNode;
            if (TopNode != null)
            {
                ls_node.Clear();
                GetNodes(TopNode);
            }
            else
            {
                MessageBox.Show("未检索到根节点");
            }
        }
        private void 加载本地文件_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Filter = "cdat文件|*.cdat|所有文件|*.*";
                openFileDialog.Multiselect = false;
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    path = openFileDialog.FileName;
                    this.Text = path;
                    Loadfile(path);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
        private void Save_Click(object sender, EventArgs e)
        {
            try
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Filter = "cdat文件|*.cdat|所有文件|*.*";
                var res = saveFileDialog.ShowDialog();
                if (res == DialogResult.OK)
                {
                    string fileName = saveFileDialog.FileName;
                    Operate.SaveJsonToFile(fileName);
                    this.Text = fileName;
                    path = fileName;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 获取treeView所有节点并保存到list中
        /// </summary>
        /// <param name="Topnode"></param>
        private void GetNodes(TreeNode Topnode)
        {
            if (Topnode.Nodes.Count > 0)
            {
                ls_node.Add(Topnode);
                for (int i = 0; i < Topnode.Nodes.Count; i++)
                {
                    GetNodes(Topnode.Nodes[i]);
                }
            }
            else
            {
                ls_node.Add(Topnode);
            }
        }
        /// <summary>
        /// 绑定json数据到treeView
        /// </summary>
        /// <param name="treeView"></param>
        /// <param name="strJson"></param>
        private void Binding(TreeView treeView, string strJson)
        {
            try
            {
                treeView.Nodes.Clear();//清空Node
                if (IsJOjbect(strJson))
                {
                    JObject jo = (JObject)JsonConvert.DeserializeObject(strJson);
                    foreach (var joitem in jo)
                    {
                        TreeNode jotree = null;
                        if (joitem.Value.GetType() == typeof(JObject))
                        {
                            if (joitem.Key == "Comments")
                            {
                                continue;
                            }
                            jotree = new TreeNode(joitem.Key);
                            AddTreeChildNode(ref jotree, joitem.Value.ToString());
                            treeView.Nodes.Add(jotree);
                            ls_node.Add(jotree);
                        }
                    }
                }
                treeView.ExpandAll();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        public void AddTreeChildNode(ref TreeNode parantNode, string value)
        {
            if (IsJOjbect(value))
            {
                JObject jo = (JObject)JsonConvert.DeserializeObject(value);
                foreach (var joitem in jo)
                {
                    TreeNode jotree = null;
                    if (joitem.Value.GetType() == typeof(JObject))
                    {
                        jotree = new TreeNode(joitem.Key);
                        AddTreeChildNode(ref jotree, joitem.Value.ToString());
                        parantNode.Nodes.Add(jotree);
                        ls_node.Add(jotree);
                    }
                    else if (joitem.Value.GetType() == typeof(JValue))
                    {
                        DataGridViewRow dataGridViewRow = new DataGridViewRow();
                        DataGridViewTextBoxCell dataGridViewTextBoxCell = new DataGridViewTextBoxCell();
                        DataGridViewTextBoxCell dataGridViewTextBoxCell1 = new DataGridViewTextBoxCell();
                        DataGridViewTextBoxCell dataGridViewTextBoxCell2 = new DataGridViewTextBoxCell();
                        dataGridViewRow.Cells.Add(dataGridViewTextBoxCell);
                        dataGridViewRow.Cells.Add(dataGridViewTextBoxCell1);
                        dataGridViewRow.Cells.Add(dataGridViewTextBoxCell2);
                        bool ret = dataGridViewRow.SetValues(joitem.Key.ToString(), joitem.Value.ToString(), joitem.Value.Type.ToString());
                    }
                }
            }

        }
        public bool IsJOjbect(string value)
        {
            try
            {
                JObject ja = JObject.Parse(value);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public bool IsJArray(string value)
        {
            try
            {
                JArray ja = JArray.Parse(value);
                return true;

            }
            catch (Exception ex)
            {
                return false;
            }
        }

        public bool IsVarArray(string value)
        {
            try
            {
                bool a = true;
                JArray ja = JArray.Parse(value);
                foreach (var item in ja)
                {
                    if (item.GetType() != typeof(JObject))
                    {
                        a = false;
                        break;
                    }
                }
                return a;
            }
            catch (Exception)
            {
                return false;
            }
        }



        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            try
            {
                if (treeView1.SelectedNode != null)
                {
                    CurrentSelectedNode = treeView1.SelectedNode;
                }
                TreeNode CurrentNode = CurrentSelectedNode;
                dataGridView1.Rows.Clear();
                //获取当前树状图节点的keyName
                string keyName = GetKeyName();
                if (keyName == null)
                {
                    return;
                }

                JObject jsonData = (JObject)JsonConvert.DeserializeObject(jsonStr);
                string[] keys = keyName.Split('.');
                JObject current = jsonData;

                for (int i = 0; i < keys.Length - 1; i++)
                {
                    if (current[keys[i]] is JObject next)
                    {
                        current = next;
                    }
                    else if (current[keys[i]] is null || !(current[keys[i]] is JObject))
                    {
                        throw new Exception($"Key path not found: {String.Join(".", keys[i])}");
                    }
                }

                string originalKey = keys[keys.Length - 1];
                current = current[originalKey] as JObject;

                foreach (var joitem in current)
                {
                    if (joitem.Value.GetType() == typeof(JValue))
                    {
                        DataGridViewRow dataGridViewRow = new DataGridViewRow();
                        DataGridViewTextBoxCell dataGridViewTextBoxCell = new DataGridViewTextBoxCell();
                        DataGridViewTextBoxCell dataGridViewTextBoxCell1 = new DataGridViewTextBoxCell();
                        DataGridViewTextBoxCell dataGridViewTextBoxCell2 = new DataGridViewTextBoxCell();
                        dataGridViewRow.Cells.Add(dataGridViewTextBoxCell);
                        dataGridViewRow.Cells.Add(dataGridViewTextBoxCell1);
                        dataGridViewRow.Cells.Add(dataGridViewTextBoxCell2);
                        bool ret = dataGridViewRow.SetValues(joitem.Key.ToString(), joitem.Value.ToString(), joitem.Value.Type.ToString());
                        dataGridView1.Rows.Add(dataGridViewRow);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            if (dataGridView1.Rows.Count > 0)
            {
                dataGridView1.Rows[0].Selected = false;
            }


            tKey.Text = "";
            tValue.Text = "";
            cType.SelectedIndex = -1;
            groupBox1.Enabled = false;
            richTextBoxComments.Text = "";




        }

        private void 添加_Click(object sender, EventArgs e)
        {
            try
            {

                string keyName = GetKeyName();
                if (keyName == null)
                {
                    return;
                }
                if (keyName.Split('.').Length > 2)
                {
                    MessageBox.Show("无法继续添加层级");
                    return;
                }
                FormAdd add = new FormAdd(keyName, true);
                add.sendData += (key, valueType, value, jo) =>
                {
                    Operate.AddKeyValueClass(key);
                    NodeFullpath = CurrentSelectedNode.FullPath + "\\" + key.Split('.').Last();
                    RefreshTreeView();
                };
                add.StartPosition = FormStartPosition.CenterParent;
                add.ShowDialog();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }


        private void 复制_Click(object sender, EventArgs e)
        {
            try
            {
                string keyName = GetKeyName();
                if (keyName == null)
                {
                    return;
                }
                string[] vv = keyName.Split('.');
                vv[vv.Length - 1] = CurrentSelectedNode.Text + "_copy";
                string newKyeName = string.Join(".", vv);
                Operate.copyKeyAtSameLevelWithNewName(keyName, CurrentSelectedNode.Text + "_copy");
                NodeFullpath = CurrentSelectedNode.FullPath;
                RefreshTreeView();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void 编辑_Click(object sender, EventArgs e)
        {
            try
            {
                if (treeView1.SelectedNode != null)
                {
                    //开启节点编辑
                    treeView1.LabelEdit = true;
                    if (!treeView1.SelectedNode.IsEditing)
                    {
                        treeView1.SelectedNode.BeginEdit();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void 删除_Click(object sender, EventArgs e)
        {
            try
            {
                string keyName = GetKeyName();
                if (keyName == null)
                {
                    return;
                }
                Operate.Delete(keyName);
                NodeFullpath = CurrentSelectedNode.FullPath;
                RefreshTreeView();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private string GetKeyName()
        {
            try
            {
                TreeNode CurrentNode = CurrentSelectedNode;
                string keyName = "";
                if (CurrentNode == null)
                {
                    MessageBox.Show("请先选中节点");
                    return null;
                }
                int level = CurrentNode.Level;
                for (int i = 0; i < level + 1; i++)
                {
                    if (CurrentNode.Parent != null)
                    {
                        keyName = keyName == "" ? CurrentNode.Text : keyName.Insert(0, CurrentNode.Text + ".");
                        CurrentNode = CurrentNode.Parent;
                    }
                    else
                    {
                        keyName = keyName == "" ? CurrentNode.Text : keyName.Insert(0, CurrentNode.Text + ".");
                    }
                }
                return keyName;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return null;
            }
        }

        private void treeView1_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            try
            {
                treeView1.SelectedNode.EndEdit(true);
                //编辑完成，关闭编辑模式，不关闭编辑模式，双击节点时，会启动编辑
                treeView1.LabelEdit = false;

                string keyName = GetKeyName();
                if (keyName == null)
                {
                    return;
                }
                if (e.Label == null)
                {
                    return;
                }
                //e.Label：获取编辑后的名称，当前Node其他属性并未改变
                string lab = e.Label;

                Operate.ModifyKeyName(keyName, lab);

                //遍历ls_node中之前保存的Node，判断是否和当前节点一致
                foreach (var item in ls_node)
                {
                    if (item == e.Node)
                    {
                        //节点一致，修改ls_node中保存Node的节点名称
                        item.Text = e.Label;
                    }
                }
                jsonStr = Operate.LoadJsonFromFile(path);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {

            try
            {
                int index = e.RowIndex;
                if (index < 0)
                {
                    return;
                }
                tKey.Text = dataGridView1.Rows[index].Cells[0].Value.ToString();
                //Tag中存放初始值，后面点击更新按钮时判断是否变化
                tKey.Tag = dataGridView1.Rows[index].Cells[0].Value.ToString();

                tValue.Text = dataGridView1.Rows[index].Cells[1].Value.ToString();
                cType.Text = dataGridView1.Rows[index].Cells[2].Value.ToString();

                GetComments();

                groupBox1.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void GetComments()
        {
            string keyName = GetKeyName();
            if (keyName == null)
            {
                return;
            }
            keyName = keyName + "." + tKey.Text;
            string lang = Thread.CurrentThread.CurrentUICulture.Name;
            string data = Operate.GetComments("Comments", keyName, lang);

            richTextBoxComments.Text = data;
        }

        private void 添加值_Click(object sender, EventArgs e)
        {
            try
            {

                // string mkey = GetKeyName() + "." + dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[0].Value.ToString();
                string mkey = GetKeyName();
                if (mkey == null)
                {
                    return;
                }
                FormAdd add = new FormAdd(mkey);
                add.sendData += (key, valueType, value, jo) =>
                {
                    JToken jk;
                    if (valueType == JValueType.Integer.ToString())
                    {
                        int ivalue = int.Parse(value);
                        jk = JToken.FromObject(ivalue);
                        // jk = JToken.Parse(value);
                        Operate.AddKeyValue(key, ivalue);
                    }
                    else if (valueType == JValueType.Float.ToString())
                    {
                        double dvalue = double.Parse(value);
                        jk = JToken.FromObject(dvalue);
                        //jk = JToken.Parse(dvalue);
                        Operate.AddKeyValue(key, jk);
                    }
                    else if (valueType == JValueType.String.ToString())
                    {
                        jk = JToken.FromObject(value);
                        Operate.AddKeyValue(key, value);
                    }
                    else if (valueType == JValueType.Boolean.ToString())
                    {
                        bool bvalue = bool.Parse(value);
                        jk = JToken.FromObject(bvalue);
                        //jk = JToken.Parse(dvalue);
                        Operate.AddKeyValue(key, jk);
                    }

                    //添加comments
                    Operate.AddJobject("Comments", key, jo);
                };

                add.StartPosition = FormStartPosition.CenterParent;

                string lang = Thread.CurrentThread.CurrentUICulture.Name;
                languageConverter.changeLanguage(add, lang);

                add.ShowDialog();
                if (add.DialogResult == DialogResult.OK)
                {
                    NodeFullpath = CurrentSelectedNode.FullPath;
                    RefreshTreeView();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void 复制值_Click(object sender, EventArgs e)
        {
            try
            {
                int index = -1;

                if (dataGridView1.CurrentRow == null || !dataGridView1.CurrentRow.Selected)
                {
                    MessageBox.Show("请先选中要复制的行");
                    return;
                }
                index = dataGridView1.CurrentRow.Index;

                var key = dataGridView1.Rows[index].Cells[0].Value.ToString();
                var value = dataGridView1.Rows[index].Cells[1].Value.ToString();
                var type = dataGridView1.Rows[index].Cells[2].Value.ToString();
                string keyName = GetKeyName();
                if (keyName == null)
                {
                    return;
                }
                keyName = keyName + "." + key;
                string newKeyName = key + "_copy";
                Operate.copyKeyAtSameLevelWithNewName(keyName, newKeyName);
                NodeFullpath = CurrentSelectedNode.FullPath;
                RefreshTreeView();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void 删除值_Click(object sender, EventArgs e)
        {
            try
            {
                var row = dataGridView1.CurrentRow;
                if (dataGridView1.CurrentRow == null || !dataGridView1.CurrentRow.Selected)
                {
                    MessageBox.Show("请先选中要删除的行");
                    return;
                }
                string keyName = GetKeyName();
                if (keyName == null)
                {
                    return;
                }
                Operate.Delete(keyName + "." + dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[0].Value.ToString());
                NodeFullpath = CurrentSelectedNode.FullPath;
                RefreshTreeView();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        int selectedIndex;
        private void 修改值_Click(object sender, EventArgs e)
        {
            try
            {
                //当前选中的行
                selectedIndex = dataGridView1.SelectedRows[0].Index;
                string keyName;
                string mkeyName = GetKeyName();
                if (mkeyName == null)
                {
                    return;
                }
                keyName = mkeyName + "." + tKey.Tag.ToString();
                JToken jk =null;
                switch (cType.Text)
                {
                    case "Integer":
                        if (!int.TryParse(tValue.Text, out int ivalue))
                        {
                            MessageBox.Show("数据格式与输入数据不匹配");
                            return;
                        }
                        else
                        {
                            int iivalue = int.Parse(tValue.Text);
                            jk = JToken.FromObject(iivalue);
                        }
                        break;
                    case "Float":
                        if (!float.TryParse(tValue.Text, out float fvalue))
                        {
                            MessageBox.Show("数据格式与输入数据不匹配");
                            return;
                        }
                        else
                        {
                            float ffvalue = float.Parse(tValue.Text);
                            jk = JToken.FromObject(ffvalue);
                        }
                        break;
                    case "Boolean":
                        if (!bool.TryParse(tValue.Text, out bool bvalue))
                        {
                            MessageBox.Show("数据格式与输入数据不匹配");
                            return;
                        }
                        else
                        {
                            bool bbvalue = bool.Parse(tValue.Text);
                            jk = JToken.FromObject(bbvalue);
                        }
                        break;
                    case "String":
                      
                            string ssvalue = tValue.Text;
                            jk = JToken.FromObject(ssvalue);
                       
                        break;
                }
                if (tKey.Tag.ToString() != tKey.Text)  //判断键是否修改
                {
                    string newKeyName = tKey.Text.ToString();


                    //if (valueType == JValueType.Integer.ToString())
                    //{
                    //    //int ivalue = int.Parse(value);
                    //    //jk = JToken.FromObject(ivalue);
                    //    // jk = JToken.Parse(value);
                    //    Operate.AddKeyValue(key, ivalue);
                    //}
                    //else if (valueType == JValueType.Float.ToString())
                    //{
                    //    double dvalue = double.Parse(value);
                    //    jk = JToken.FromObject(dvalue);
                    //    //jk = JToken.Parse(dvalue);
                    //    Operate.AddKeyValue(key, jk);
                    //}
                    //else if (valueType == JValueType.String.ToString())
                    //{
                    //    jk = JToken.FromObject(value);
                    //    Operate.AddKeyValue(key, value);
                    //}
                    //else if (valueType == JValueType.Boolean.ToString())
                    //{
                    //    bool bvalue = bool.Parse(value);
                    //    jk = JToken.FromObject(bvalue);
                    //    //jk = JToken.Parse(dvalue);
                    //    Operate.AddKeyValue(key, jk);
                    //}



                    Operate.ModifyKeyName(keyName, newKeyName);
                    Operate.ModifyValue(newKeyName, jk);
                }
                else
                {
                    Operate.ModifyValue(keyName, jk);
                }
               

                NodeFullpath = CurrentSelectedNode.FullPath;
                RefreshTreeView();



                dataGridView1.Rows[selectedIndex].Selected = true;
                dataGridView1_CellClick(dataGridView1, new DataGridViewCellEventArgs(0, selectedIndex));

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        string NodeFullpath;


        private void RefreshTreeView()
        {
            try
            {
                treeView1.Nodes.Clear();
                jsonStr = Operate.LoadJsonFromFile(path);
                Binding(this.treeView1, jsonStr);
                var TopNode = treeView1.TopNode;
                ls_node.Clear();
                GetNodes(TopNode);

                //treeView1.Focus();
                foreach (var item in ls_node)
                {
                    if (item.FullPath == NodeFullpath)
                    {
                        treeView1.SelectedNode = item;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(path))
            {
                jsonStr = Operate.LoadJsonFromFile(path);
                Binding(this.treeView1, jsonStr);
                var TopNode = treeView1.TopNode;
                ls_node.Clear();
                GetNodes(TopNode);
            }

        }

        private void treeView1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.All;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        private void treeView1_DragDrop(object sender, DragEventArgs e)
        {
            string[] data = (string[])e.Data.GetData(DataFormats.FileDrop, false);  //获取拖入文件的路径
            path = data[0];
            this.Text = path;
           
            Loadfile(path);
        }

        private void menuItemLangChinese_Click(object sender, EventArgs e)
        {
            languageConverter.changeLanguage(this, "zh");
            if (treeView1.Nodes.Count != 0)
            {
                GetComments();
            }

        }

        private void menuItemLangEnglish_Click(object sender, EventArgs e)
        {
            languageConverter.changeLanguage(this, "en");
            if (treeView1.Nodes.Count != 0)
            {
                GetComments();
            }
        }

        private void menuItemLangGerman_Click(object sender, EventArgs e)
        {
            languageConverter.changeLanguage(this, "de");
            if (treeView1.Nodes.Count != 0)
            {
                GetComments();
            }
        }

        //创建新的
        private void menuItemFileNew_Click(object sender, EventArgs e)
        {
            string cdat = @"{'Root':{},'Comments':{}}";
            File.WriteAllText("Temp.cdat", cdat);
            path = "Temp.cdat";
            this.Text = "";
            Loadfile(path);
        }


    }
    public enum JValueType
    {
        Integer,
        Float,
        String,
        Boolean
    }
}
